package com.aliang.shopping.security.auth;

import cn.hutool.core.util.StrUtil;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.contact.BasicConstant;
import com.aliang.shopping.exception.SecurityException;
import com.aliang.shopping.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从http请求的header中获取token
        String token = request.getHeader(BasicConstant.HEADER_NAME);
        if (StrUtil.isBlank(token)) {
            // 如果没拿到，从参数里再拿一次
            token = request.getParameter(BasicConstant.HEADER_NAME);
        }
        // 2. 开始执行认证
        try {
            if (!JwtUtil.verifyToken(token)) {
                throw new SecurityException(ResultCodeEnum.USER_NOT_LOGIN);
            }
        } catch (Exception e) {
            throw new SecurityException(ResultCodeEnum.TOKEN_INVALID);
        }

        // 获取载荷
        Payload payload = JwtUtil.getPayload(token);
        // 将载荷放入线程变量
        UserHolder.set(payload);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 移除线程变量中的数据，避免内存泄露
        UserHolder.remove();
    }
}